"""
BoLe HR Platform - 主入口文件
启动智能招聘多智能体平台
"""

import asyncio
import typer
from typing import Optional
import uvicorn
from pathlib import Path

from src.core.config import config
from src.core.container import container, setup_default_services
from src.core.events import event_bus, SystemEvents
from src.core.plugins import plugin_manager

app = typer.Typer(help="BoLe HR Platform - 智能招聘多智能体平台")


async def init_system():
    """初始化系统"""
    print("🚀 Initializing BoLe HR Platform...")
    
    # 启动事件总线
    await event_bus.start()
    await event_bus.publish(SystemEvents.SYSTEM_STARTED, {
        "version": config.system.version,
        "debug": config.system.debug
    })
    
    # 设置默认服务
    await setup_default_services()
    
    # 加载插件
    await plugin_manager.load_plugins_from_config()
    
    print("✅ System initialized successfully!")


async def cleanup_system():
    """清理系统"""
    print("🛑 Shutting down BoLe HR Platform...")
    
    # 清理插件
    await plugin_manager.cleanup_all()
    
    # 停止事件总线
    await event_bus.publish(SystemEvents.SYSTEM_STOPPED, {})
    await event_bus.stop()
    
    print("✅ System shutdown complete!")


@app.command()
def serve(
    host: str = typer.Option("0.0.0.0", help="服务器主机地址"),
    port: int = typer.Option(8000, help="服务器端口"),
    reload: bool = typer.Option(True, help="开发模式热重载"),
):
    """启动API服务器"""
    
    async def startup():
        await init_system()
        
    async def shutdown():
        await cleanup_system()
    
    # 配置uvicorn
    uvicorn_config = uvicorn.Config(
        "src.services.api.main:app",
        host=host,
        port=port,
        reload=reload,
        log_level="info"
    )
    
    server = uvicorn.Server(uvicorn_config)
    
    # 运行服务器
    try:
        asyncio.run(startup())
        asyncio.run(server.serve())
    except KeyboardInterrupt:
        asyncio.run(shutdown())


@app.command()
def process_data(
    data_path: str = typer.Argument(help="数据文件路径"),
    batch_size: int = typer.Option(10, help="批处理大小"),
):
    """处理数据文件"""
    
    async def run_processing():
        await init_system()
        
        try:
            # 这里会调用数据处理管道
            from src.lightrag_engine.ingestion.pipeline import IngestionPipeline
            
            pipeline = await container.resolve(IngestionPipeline)
            await pipeline.process_file(data_path, batch_size)
            
        finally:
            await cleanup_system()
    
    asyncio.run(run_processing())


@app.command()
def query(
    question: str = typer.Argument(help="查询问题"),
    mode: str = typer.Option("hybrid", help="检索模式: vector/keyword/graph/hybrid"),
):
    """执行查询"""
    
    async def run_query():
        await init_system()
        
        try:
            # 这里会调用查询引擎
            from src.services.api.query_service import QueryService
            
            query_service = await container.resolve(QueryService)
            result = await query_service.process_query(question, mode)
            
            print("📋 查询结果:")
            print(result)
            
        finally:
            await cleanup_system()
    
    asyncio.run(run_query())


@app.command()
def agent_task(
    task_description: str = typer.Argument(help="任务描述"),
    agent_type: str = typer.Option("orchestrator", help="智能体类型"),
):
    """执行智能体任务"""
    
    async def run_task():
        await init_system()
        
        try:
            from src.agents.orchestrator.main_orchestrator import MainOrchestrator
            from src.core.interfaces import Task, TaskStatus
            
            orchestrator = await container.resolve(MainOrchestrator)
            task = Task(
                id=f"cli_task_{asyncio.get_event_loop().time()}",
                description=task_description,
                task_type="user_request"
            )
            
            result = await orchestrator.orchestrate_task(task)
            
            print("🤖 任务执行结果:")
            print(f"状态: {result.status.value}")
            if result.result:
                print(f"结果: {result.result}")
            
        finally:
            await cleanup_system()
    
    asyncio.run(run_task())


@app.command()
def list_plugins():
    """列出已加载的插件"""
    
    async def run_list():
        await init_system()
        
        plugins = plugin_manager.list_plugins()
        if plugins:
            print("🔌 已加载的插件:")
            for plugin_name in plugins:
                plugin = plugin_manager.get_plugin(plugin_name)
                print(f"  - {plugin_name} (v{plugin.version})")
        else:
            print("📭 没有加载任何插件")
        
        await cleanup_system()
    
    asyncio.run(run_list())


@app.command()
def config_info():
    """显示配置信息"""
    print("⚙️  系统配置信息:")
    print(f"名称: {config.system.name}")
    print(f"版本: {config.system.version}")
    print(f"调试模式: {config.system.debug}")
    print(f"日志级别: {config.system.log_level}")
    
    # 显示各层配置
    print("\n📊 数据层配置:")
    data_config = config.get("data_layer", {})
    for layer, settings in data_config.items():
        provider = settings.get("provider", "unknown")
        print(f"  {layer}: {provider}")


if __name__ == "__main__":
    app()